<template>
  <div class="login-panel">
    <div class="title drag">微信</div>
    <div v-if="showLoading" class="loading-panel">
      <img src="../assets/img/loading.gif" />
    </div>
    <div class="login-form" v-else>
      <div class="error-msg">{{ errorMsg }}</div>

      <el-form
        ref="formDataRef"
        :model="formData"
        label-width="0px"
        @keydown.enter="doLogin"
      >
        <!-- 邮箱 -->
        <el-form-item>
          <div class="email-panel">
            <el-input
              class="input"
              size="large"
              clearable
              placeholder="请输入邮箱"
              v-model.trim="formData.email"
              maxLength="30"
              @focus="clearVerify"
              :input-style="{ border: 'none' }"
            >
              <template #prefix>
                <span class="iconfont icon-youxiang"></span>
              </template>
            </el-input>

            <el-dropdown
              trigger="click"
              max-height="200"
              v-if="isLogin && localUserList.length > 0"
            >
              <span class="iconfont icon-xiala"></span>

              <template #dropdown>
                <el-dropdown-menu v-for="item in localUserList">
                  <div class="email-select" @click="selectEmail(item.email)">
                    {{ item.email }}
                  </div>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-form-item>

        <!-- 昵称 -->
        <el-form-item v-if="!isLogin">
          <el-input
            size="large"
            clearable
            v-model.trim="formData.nickName"
            placeholder="请输入昵称"
            maxLength="15"
            @focus="clearVerify"
          >
            <template #prefix>
              <span class="iconfont icon-icon-user"></span>
            </template>
          </el-input>
        </el-form-item>

        <!-- 登录密码 -->
        <el-form-item label="">
          <el-input
            type="password"
            size="large"
            v-model="formData.password"
            placeholder="请输入密码"
            show-password
            @focus="clearVerify"
          >
            <template #prefix>
              <span class="iconfont icon-mima"></span>
            </template>
          </el-input>
        </el-form-item>

        <!-- 再次输入密码 -->
        <el-form-item prop="rePassword" v-if="!isLogin">
          <el-input
            type="password"
            size="large"
            placeholder="请再次输入密码"
            v-model.trim="formData.rePassword"
            show-password
            @focus="clearVerify"
          >
            <template #prefix>
              <span class="iconfont icon-mima"></span>
            </template>
          </el-input>
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item>
          <div class="check-code-panel">
            <el-input
              size="large"
              placeholder="请输入验证码"
              v-model.trim="formData.checkCode"
              @focus="clearVerify"
            >
              <template #prefix>
                <span class="iconfont icon-yanzhengyanzhengma"></span>
              </template>
            </el-input>
            <img
              :src="checkCodeUrl"
              class="check-code"
              @click="changeCheckCode"
            />
          </div>
        </el-form-item>

        <!-- 登录/注册 -->
        <el-form-item>
          <el-button
            type="primary"
            class="login-btn"
            @click="doLogin"
            color="#07c160"
          >
            {{ isLogin ? "登录" : "注册" }}
          </el-button>
        </el-form-item>

        <!-- 切换 -->
        <div class="bottom-link">
          <span class="a-link no-account" @click="changeOpType">{{
            isLogin ? "没有账号?" : "已有账号?"
          }}</span>
        </div>
      </el-form>
    </div>
  </div>

  <WinOption
    :show-set-top="false"
    :show-min="false"
    :show-max="false"
  ></WinOption>
</template>

<script setup lang="ts">
import { nextTick, onMounted, ref } from "vue";
import WinOption from "@/components/WinOption.vue";
import { getCheckCode, userLogin, userRegister } from "@/api/account/login";
import common from "@/utils/common";
import Verify from "@/utils/verify";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/store/useUserStore";
import { useRouter } from "vue-router";
import md5 from "js-md5";

const userStore = useUserStore();
console.log("userStore111====>", userStore);
const router = useRouter();

const isLogin = ref(true);
const showLoading = ref(false);
const formDataRef = ref();

const localUserList = ref<any>([]); // 本地用户列表

const errorMsg = ref("");
// 验证码url
const checkCodeUrl = ref("");

// 提交的数据
const formData = ref({
  email: "",
  nickName: "",
  password: "",
  rePassword: "",
  checkCode: "",
});

onMounted(() => {});

// 改变操作类型
const changeOpType = () => {
  // 通知渲染进程
  window.ipcRenderer.onLoginOrRegister(!isLogin.value);
  isLogin.value = !isLogin.value;
  nextTick(() => {
    formDataRef.value.resetFields();
    formData.value = {
      email: "",
      nickName: "",
      password: "",
      rePassword: "",
      checkCode: "",
    };

    changeCheckCode();
    clearVerify();
  });
};

// 清除校验内容
const clearVerify = () => {
  errorMsg.value = "";
};

//选择邮箱
const selectEmail = (email: string) => {
  formData.value.email = email;
};

/**
 * 校验数据
 * @param type
 * @param value
 * @param msg
 */
const checkValue = (type: any, value: any, msg: string) => {
  if (common.isEmpty(value)) {
    errorMsg.value = msg;
    return false;
  }

  if (type && !Verify[type](value)) {
    errorMsg.value = msg;
    return false;
  }
  return true;
};

// 调用接口，改变验证码
const changeCheckCode = async () => {
  formData.value.checkCode = "";
  const checkCodeRes: any = await getCheckCode();
  // 存储数据
  checkCodeUrl.value = checkCodeRes.data.checkCodeBase64;
  localStorage.setItem("checkCodeKey", checkCodeRes.data.code);
};

/**
 * 登录/注册操作 -- 校验
 */
const doLogin = async () => {
  clearVerify();
  if (!checkValue("checkEmail", formData.value.email, "请输入正确的邮箱")) {
    return;
  }
  if (
    !checkValue(
      "checkPassword",
      formData.value.password,
      "密码只能是数字、字母、特殊字符8~18位"
    )
  ) {
    return;
  }
  if (!checkValue(null, formData.value.checkCode, "请输入验证码")) {
    return;
  }

  if (
    !isLogin.value &&
    !checkValue(null, formData.value.nickName, "请输入昵称")
  ) {
    return;
  }
  if (!isLogin.value && common.isEmpty(formData.value.rePassword)) {
    errorMsg.value = "请再次输入密码";
    return;
  }
  if (!isLogin.value && formData.value.password != formData.value.rePassword) {
    errorMsg.value = "两次输入的密码不一致";
    return;
  }

  if (isLogin.value) {
    showLoading.value = true;
  }

  let loginRes: any = null;
  // 判断是登录还是注册
  if (isLogin.value) {
    loginRes = await userLogin({
      email: formData.value.email,
      password: isLogin.value
        ? md5(formData.value.password)
        : formData.value.password,
      nickName: formData.value.nickName,
      checkCode: formData.value.checkCode,
      checkCodeKey: localStorage.getItem("checkCodeKey"),
    }).catch(() => {
      console.log("登录失败....");
      showLoading.value = false;
      // 重新拉取验证码
      changeCheckCode();
    });
  } else {
    loginRes = await userRegister({
      email: formData.value.email,
      password: isLogin.value
        ? md5(formData.value.password)
        : formData.value.password,
      nickName: formData.value.nickName,
      checkCode: formData.value.checkCode,
      checkCodeKey: localStorage.getItem("checkCodeKey"),
    }).catch(() => {
      console.log("注册失败....");
      showLoading.value = false;
      // 重新拉取验证码
      changeCheckCode();
    });
  }

  if (!loginRes || !loginRes.data) {
    ElMessage({
      type: "error",
      message: loginRes.message ? loginRes.message : "登录失败",
    });
    showLoading.value = false;
    // 重新拉取验证码
    changeCheckCode();
    // 重新拉取验证码
    return;
  }

  // 判断登录还是注册
  if (isLogin.value) {
    console.log("loginRes--->", loginRes.data);
    // 保存用户信息
    userStore.setUserInfo(loginRes.data);

    // 设置用户TOKEN
    localStorage.setItem("access_token", loginRes.data.token);

    // 跳转页面
    router.push({ path: "/main" });

    routeToMain({
      email: formData.value.email,
      token: loginRes.data.token,
      uid: loginRes.data.uid,
      nickName: loginRes.data.nickname,
    });
  } else {
    // 注册成功
    changeOpType();
    ElMessage({
      type: "success",
      message: "注册成功",
    });
  }
};

changeCheckCode();

const routeToMain = ({ email, token, uid, nickName }) => {
  const screenWidth = window.screen.width;
  const screenHeight = window.screen.height;
  if (window.ipcRenderer) {
    // 设置本地登录emai缓存
    window.ipcRenderer.onSetLocalStore({
      key: "email",
      value: formData.value.email,
    });
    window.ipcRenderer.onLoginSuccess({
      email,
      token,
      uid,
      nickName,
      screenWidth,
      screenHeight,
    });
  }
};

onMounted(() => {});
</script>

<style scoped lang="scss">
.login-panel {
  width: 100%;
  height: 100vh;
  background-color: #fff;

  .title {
    height: 30px;
    padding: 5px 0px 0px 10px;
  }

  .loading-panel {
    height: calc(100vh - 32px);
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
    img {
      width: 300px;
    }
  }

  .login-form {
    padding: 0px 15px 29px 15px;
    :deep(.el-input__wrapper) {
      box-shadow: none;
      border-radius: none;
    }

    .el-form-item {
      border-bottom: 1px solid #ddd;
    }

    .error-msg {
      line-height: 30px;
      height: 30px;
      color: #fb7373;
    }

    .email-panel {
      align-items: center;
      width: 100%;
      display: flex;
      .input {
        flex: 1;
      }
      .icon-xiala {
        margin-left: 3px;
        width: 16px;
        cursor: pointer;
        border: none;
      }
    }

    .check-code-panel {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;

      .check-code {
        cursor: pointer;
        width: 120px;
        margin-left: 5px;
      }
    }

    .login-btn {
      margin-top: 20px;
      width: 100%;
      background: #07c160;
      height: 36px;
      font-size: 16px;
    }

    .bottom-link {
      text-align: right;
    }
  }
}
</style>
